/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testalgorithm;

/**
 *
 * @author haoliang.donghl
 */
public class OrignAlgorithm extends AbstractAlgorithm{

    public static void main(String[] args) {
        int cost;
        int ret;
        int citr;

        if (args.length > 0) {
            DICTIONARY_NAME = args[0];
        }
        readParameter(DICTIONARY_NAME + "\\info.txt");

        matrixIn = new int[NUM_APP][NUM_MACHINE];
        matrixOut = new int[NUM_APP][NUM_MACHINE];
        matrixCost = new int[NUM_APP][NUM_MACHINE];
        matrixState = new float[NUM_APP][NUM_MACHINE];
        vectorAppSize = new int[NUM_APP];
        vectorAppCPU = new float[NUM_APP];
        vectorMachineCPU = new float[NUM_MACHINE];
        readFromFile(DICTIONARY_NAME);

        printAppNeeds();
        checkConstraint(matrixIn);
        printMachineCPU();
        calculateMatrixCost(matrixIn);

        //System.out.println("===================================");

        copyArray(matrixOut, matrixIn);
        citr = 0;
        while ((ret = checkConstraint(matrixOut)) != -1 && citr < NUM_APP){
            doAssign(matrixOut, ret);
            citr++;
        }
        printMachineCPU();

        cost = calculateCost();
        printMatrixInOut(matrixOut, DICTIONARY_NAME + "\\out.txt");
        //System.out.print("The Cost is ");
        //System.out.println(cost);
    }

    private static void doAssign(int[][] matrix, int p) {
        float diff = vectorMachineCPU[p] - CPU_UP_BOUND;
        float minDiff = Float.MAX_VALUE, value;
        int minID = 0;
        int[] minVector, tempVector;
        minVector = new int[NUM_MACHINE];
        tempVector = new int[NUM_MACHINE];
        for (int i = 0; i < NUM_APP; i++){
            if (minDiff > (diff - matrixState[i][p]) &&
                    diff - matrixState[i][p] > 0){
                doMoveTo(matrix[i], p, i, tempVector, diff);
                minDiff = diff - matrixState[i][p];
                minID = i;
                for (int j = 0; j < NUM_MACHINE; j++){
                    minVector[j] = tempVector[j];
                }
            }
        }
        for (int j = 0; j < NUM_MACHINE; j++){
            matrix[minID][j] = minVector[j];
        }
    }

    private static void doMoveTo(int[] input, int p, int app, int[] output, float diff){
        float minValue = Float.MAX_VALUE;
        int minID = 0;
        for (int i = 0; i < NUM_MACHINE; i++){
            if (i != p && i != 2 && matrixState[app][p] + vectorMachineCPU[i] < CPU_UP_BOUND){
                if (minValue > matrixCost[app][i]){
                    minID = i;
                    minValue = matrixCost[app][i];
                }
            }
        }
        input[p] = 1;
        output[minID] = 2;
    }
}
